package com.example.testnetty.netty;

import android.util.Log;

import com.example.testnetty.activity.MainActivity;
import com.example.testnetty.utlis.EnttyUtlis;
import com.example.testnetty.utlis.RTKAccount;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import static com.example.testnetty.netty.Constans.HOST;
import static com.example.testnetty.netty.Constans.TCP_PORT;

public class NettyClientRtk {

    private static ChannelFuture f;


    public void start(){
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    //.option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast("decoder", new ByteArrayDecoder());
                            p.addLast("encoder",new ByteArrayEncoder());
                            p.addLast("handler",new MainActivity.RtkClientHandler());
                        }
                    });

            // Start the client.
            f = b.connect(HOST, TCP_PORT).sync();
            String authRequest = EnttyUtlis.createNtripStr(RTKAccount.getMount(), RTKAccount.getUsername(), RTKAccount.getPassword());//9091
            f.channel().writeAndFlush(authRequest.getBytes());
            // Wait until the connection is closed.
//            f.channel().closeFuture().sync().channel();
            f.sync().channel();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // Shut down the event loop to terminate all threads.
            group.shutdownGracefully();
        }
    }


}
